<?php
namespace Live\Controller;
require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
use Live\Controller\CommonController;

class LiveController extends CommonController
{
    public function index(){
        $this->display();
    }
    
    /*public function live_list() {
        $model=M('Live');
        //$total = $model->group('group_id')->count();
//        $page = new \Think\Page($total, 25);
//        $show = $page->show();

        $liveList = $model
            ->alias('live')
            ->group('group_id')
//            ->join('__USER_INFO__ u ON u.uid=live.user_id','left')
            ->order('id DESC')
//            ->limit($page->firstRow .',' . $page->listRows)
            ->select();

//        $this->assign('showpage', $show);
        $this->assign('liveList', $liveList);
        $this->display();
    }*/

    public function live_list() {
        list($liveList, $groups, $auth_group, $channel, $show) = $this->getLiveList();

//        $Page = new \Think\Page(count($liveList), 15);
//        $show = $Page->show();

//        $splitArr = array_slice($liveList, $Page->firstRow, $Page->listRows);
        if($channel) {
            if($channel == '*') {
              $channelList = M('Channel')->select();
            } else {
              $channelList = M('Channel')->where(array('in', explode(',', $channel)))->select();
            }
        }
        $reporter=M('User_info')->field("realname,mobile,realnamepy,uid")->select();

        $this->assign('channelList', $channelList);
        $this->assign('reporter', $reporter);
        $this->assign('pageshow', $show);
        $this->assign('liveList', $liveList);
        $this->display();
    }


    public function  liveInfo(){
        $group_id = I('get.group_id');
        $uid = session('liveadmin_uid');
        $is_admin = session('is_admin');
        if($group_id){
            list($liveList, $groups, $auth_group, $channel) = $this->getLiveList();

            $is_ext = M('Live')->where(array('group_id' => $group_id))->find();
            if(!$is_ext)
                $this->error('对不起，此直播不存在！',U('live_list'));

            if(!$is_admin) {
                if(in_array($group_id, $groups)) {
                    $model=M('Live');
                    $streamList = $model
                                ->alias('live')
                                ->where(array('group_id'=>$group_id))
                                ->join('__USER_INFO__ u ON u.uid=live.user_id','left')
                                ->order('pos_sort asc, id DESC')
                                ->select();  

                    $auth = M('LiveAuth')->where(array('group_id' => $group_id, 'user_id' => $uid))->find();             
                } else {
                    $this->error('对不起，您没有权限！',U('live_list'));
                }
            } else {

                $model=M('Live');
                $streamList = $model
                    ->alias('live')
                    ->where(array('group_id'=>$group_id))
                    ->join('__USER_INFO__ u ON u.uid=live.user_id','left')
                    ->order('pos_sort asc, id DESC')
                    ->select();

                $channel = M('Admin')->where(array('id' => $uid))->getField('liveauth');   

                // if($uid != 1) {
                if($channel != '*') {

                    if(!in_array($streamList[0]['column_id'], explode(',', $channel))) {
                        $this->error('对不起，您没有权限！',U('live_list'));
                    }
                } else {
                    $liveList = $model
                        ->where(array('v_status' => 1))
                        ->group('group_id')
                        ->order('start_time DESC')
                        ->select();
                     $this->assign('is_super',1);                     
                }



                $auth['is_scan'] = 1;
                $auth['is_manage'] = 1;             
            }

            $subQuery = 'SELECT COUNT(t.id) total FROM (SELECT id FROM `whtvjw_pv` WHERE `group_id` = "' . $group_id . '" GROUP BY ip) t';
            $seeTotal = M()->query($subQuery);

            $reporter_total = $this->getReporterList();
            $reporter_group = $this->getReporterListByGroup($group_id);

            //七牛对象存储的上传凭证
            $putPolicy=array(
                'saveKey'=>'liveList/$(etag)',
            );
            $upAuth = new Auth(C('QINIU_accessKey'), C('QINIU_secretKey'));
            $bucket = C('QINIU_BUCKET');
            $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);
            $putPolicy['returnUrl']='http://'.I('server.HTTP_HOST').U('uploadLiveThumb');
            $putPolicy['returnBody']=json_encode(array(
                "filename"=>"$(key)",
                "liveId"=>"$(x:liveId)"
            ));
            $liveToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);



            $this->assign('uploadToken', $uploadToken);
            $this->assign('liveToken', $liveToken);
            $this->assign('liveList', $liveList);
            $this->assign('streamList', $streamList);
            $this->assign('auth', $auth);
            $this->assign('is_admin', $is_admin);
            $this->assign('reporterTotal', $reporter_total);
            $this->assign('reporterGroup', $reporter_group);
            $this->assign('seeTotal', $seeTotal[0]['total']);
            $this->display();            
        } else {
             $this->error('参数错误' );
        }
    }


    public function setLiveThumb(){
        $filename=I('get.filename');
        $liveId=I('get.liveId');

        if($filename && $liveId){
            $r=M('Live')->save(array('thumb'=>C('IMAGE_HOST').$filename,'id'=>$liveId));
            if($r){
                $this->success('上传成功');
            }else{
                $this->error('上传失败',U('liveInfo'));
            }
        }

    }


    public function checkAuth($group_id) {
        $is_admin = session('is_admin');
        $uid = session('liveadmin_uid');
        list($liveList, $groups, $auth_group, $channel) = $this->getLiveList();
        if(!in_array($group_id, $auth_group) && !$is_admin) {
            $this->error('对不起，您没有权限！',U('live_list'));
            exit;
        } elseif($is_admin) {
            if($channel != "*") {
                $currChannel = M('Live')->where(array('group_id' => $group_id))->getField('column_id');
                if(!in_array($currChannel, explode(',', $channel))) {
                    $this->error('对不起，您没有权限！',U('live_list'));
                }               
            }
        }
    }

    public function getLiveList() {
        $is_admin = session('is_admin');
        $uid = session('liveadmin_uid');
        $channel = array(); // 能管理的频道
        $start_time = I('get.start_time', '');
        $end_time = I('get.end_time', '');
        $keyword = I('get.keyword', '');
        $channel = I('get.channel', '');

        if($start_time && !$end_time) {
            $map['start_time'] = array('gt', strtotime($start_time));
        }
        if(!$start_time && $end_time) {
            $map['start_time'] = array('lt', strtotime($end_time));
        }

        if($start_time && $end_time) {
            $map['start_time'] = array(array('gt', strtotime($start_time)), array('lt', strtotime($end_time)));
        }
        if($keyword) {
            $map['title'] = array('like', '%' . $keyword . '%');
        }

        if($channel) {
            $map['column_id'] = $channel;
        }

        if($is_admin) {

            $final_list = array();

            $channel = M('Admin')->where(array('id' => $uid))->getField('liveauth'); 
            // if($uid != 1) {
            if($channel != "*") {
                // 能管理的频道
                
                if($channel) {
                    $map['column_id'] = array('in', explode(',', $channel));
                    $map['v_status'] = 1;

                    $subQuery = M('Live')->alias('li')
                        ->join('__USER_INFO__ AS ui ON ui.uid = li.user_id')
                        ->where($map)->group('group_id')
                        ->order('li.start_time DESC')->buildSql();
                    $final_list_total = M()->table($subQuery.' a')->count();
                    $Page = new \Think\Page($final_list_total, 15);
                    $final_list = M('Live')->alias('li')
                                ->join('__USER_INFO__ AS ui ON ui.uid = li.user_id')
                                ->where($map)->group('group_id')
                                ->limit($Page->firstRow . ',' . $Page->listRows)
                                ->order('li.start_time DESC')->select();
                    $show = $Page->show();
                }
            } else {
                $map['v_status'] = 1;

                $subQuery =M('Live')
                    ->alias('live')
                    ->where($map)
                    ->group('group_id')
                    ->order('start_time DESC')
                    ->buildSql();
                $final_list_total = M()->table($subQuery.' a')->count();

                $Page = new \Think\Page($final_list_total, 15);

                $final_list = M('Live')
                        ->alias('live')
                        ->where($map)
                        ->group('group_id')
                        ->order('start_time DESC')
                            //->order('field(group_status,2,4,1,0,3),ABS(cast(unix_timestamp() as SIGNED)-cast(sort as SIGNED)) ASC, sort_by_id Desc')
                        ->limit($Page->firstRow . ',' . $Page->listRows)
                        ->select();
                $show = $Page->show();
            }
         
        } else {
            // 能管理的直播
            $live_auth_list = M('LiveAuth')->field('group_id')->where(array('user_id' => $uid))->order('id DESC')->select();

            // 能查看的直播
            $live_list = M('Live')->field('group_id')->where(array('user_id' => $uid))->select();

            $auth_group = $live_group = array();

            foreach($live_auth_list as $val) {
                $auth_group[] = $val['group_id'];
            }

            foreach($live_list as $val) {
                $live_group[] = $val['group_id'];
            }

            $groups = array_merge($auth_group, $live_group);
            $groups = array_unique($groups);

            if($groups) {
                $condition = $map;
                $condition['group_id'] = array('in', $groups);
                $condition['v_status'] = 1;

                $subQuery = M('Live')->where($condition)->group('group_id')->buildSql();
                $final_list_total = M()->table($subQuery.' a')->count();
                $Page = new \Think\Page($final_list_total, 15);

                $final_list = M('Live')->where($condition)->group('group_id')
                    ->order('field(group_status,2,4,1,0,3),ABS(cast(unix_timestamp() as SIGNED)-cast(sort as SIGNED)) ASC, sort_by_id Desc')
                    ->limit($Page->firstRow . ',' . $Page->listRows)->select();
                $show = $Page->show();

                $m_list = $s_list = array();
                foreach ($final_list as $key => $value) {
                    if(in_array($value['group_id'], $auth_group)) {
                        $value['is_manger'] =true;
                        array_push($m_list, $value);
                    } else {
                        $value['is_manger'] =false;
                        array_push($s_list, $value);
                    }
                }
                $final_list = array_merge($m_list, $s_list);
            }
        }

        
        return array($final_list, $groups, $auth_group, $channel, $show);
    }

    public function ajaxStreamOff(){
        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');

            $this->checkAuth($group_id);

            $count1 = M('Live')->where(array('group_id' => $group_id))->count();

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),0);
            if($res['status'] == 0) {
                $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 0))->count();
                if($count1 == $count2) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 0,
                    ));
                    $message['groupId'] = 0;
                }

               /*$mkHTML=new \Common\Util\makeHTML();
               $mkHTML-> ByGroupId($group_id);*/

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                foreach ($uidList as $key => $value) {
                    if($value == $liveinfo['user_id'])
                        unset($uidList[$key]);
                }

                // $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');

                // 推送管理员
                // $trans=json_encode(array('pushCode'=>300,'objectId'=>$live_id,'userId'=>0));
                // sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans));
                
                // 推送直播人
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$live_id,'userId'=>0));
                sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$liveinfo['user_id'],'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans));   

                if($message['groupId'] == 0) {
                    // 推送管理员
                    $trans=json_encode(array('pushCode'=>302,'objectId'=>$live_id,'userId'=>0));
                    sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=> '《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans)); 

                    // $liveUserList = M('Live')->where(array('group_id' => $liveinfo['group_id']))->select();
                    // $users = array();
                    // foreach($liveUserList as $val) {
                    //     if($liveinfo['user_id'] != $val) { 
                    //          $users[] = $val['user_id'];
                    //     }     
                    // }

                    // // 推送直播人
                    // $trans=json_encode(array('pushCode'=>302,'objectId'=>$live_id,'userId'=>0));
                    // sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans));

                }             

                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }
    }

    public function ajax_get_vstatus(){
        $id=I('get.id');
        if($id){
            echo M('Live')->getFieldById('v_status',$id);
        }else{
            echo -1;
        }
    }

    public function ajaxStreamOn(){
        // $live_id=I('get.liveId');
        // $stream=I('get.stream');
        // if($live_id&&$stream){
        //     $this->ajaxReturn(liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),1));
        // }

        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
            // $count1 = M('Live')->where(array('group_id' => $group_id))->count();
             $this->checkAuth($group_id);

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),1);
            if($res['status'] == 0) {
                M('Live')->where(array('id' => $live_id))->save(array(
                    'update_time' => time(),
                )); 

                $group_status = M('Live')->where(array('id' => $live_id))->getField('group_status');

                if($group_status != 1) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 1,
                    ));  
                    $message['groupId'] = 1;             
                }

               /*$mkHTML=new \Common\Util\makeHTML();
               $mkHTML-> ByGroupId($group_id);*/
                // $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 1))->count();
                // if($count1 == $count2) {
                //     $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                //         'group_status' => 1,
                //     ));
                //     $message['groupId'] = 1;
                // }

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];

                foreach ($uidList as $key => $value) {
                    if($value == $liveinfo['user_id'])
                        unset($uidList[$key]);
                }

                // $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');
                
                // 推送直播人
                $trans=json_encode(array('pushCode'=>301,'objectId'=>$live_id,'userId'=>0,'liveTitle' => $liveinfo['title']));
                sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$liveinfo['user_id'],'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));  


                if($message['groupId'] == 1) {
                    $trans=json_encode(array('pushCode'=>300,'objectId'=>$live_id,'userId'=>0));
                    sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));
                }  
                     $message['status'] = 0;
                    $message['msg'] = '操作成功';
                    $this->ajaxReturn($message);               


            } else {
                    $message['status'] = 1;
                    $message['msg'] = '服务器异常';
                    $this->ajaxReturn($message);
            }
        }

    }


    public function ajaxGroupStreamOn($group_id){
        if($group_id){
             $this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();
            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,1);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id,'z_status'=>array('neq',3)))->save(array(
                    'group_status' => 1,
                    'z_status' => 1,
                ));

               /*$mkHTML=new \Common\Util\makeHTML();
               $mkHTML-> ByGroupId($group_id);*/

                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];

                $users = array();
                foreach($ids as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value) 
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                // 管理员推送
                $trans=json_encode(array('pushCode'=>300,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));

                foreach ($ids as $key => $value) {
                   // 直播人推送
                    $trans=json_encode(array('pushCode'=>301,'objectId'=>$value['id'],'userId'=>0,'liveTitle' => $liveinfo['title']));
                    sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$value['user_id'],'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));

                }


                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }
    }


    public function ajaxGroupStreamOff($group_id){
        if($group_id){
             $this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();
            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,0);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id,'z_status'=>array('neq',3)))->save(array(
                    'group_status' => 0,
                    'z_status' => 0,
                ));

               /*$mkHTML=new \Common\Util\makeHTML();
               $mkHTML-> ByGroupId($group_id);*/

                // 推送
                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $users = array();
                foreach($ids as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value) 
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                // \Think\Log::write(implode(',', $uidList),'uidList');
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已终止','trans'=>$trans));

               // 直播人推送
                // $trans=json_encode(array('pushCode'=>301,'objectId'=>$ids[0]['id'],'userId'=>0,'liveTitle' => $liveinfo['title']));
                // sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播已终止','trans'=>$trans));

                foreach ($ids as $key => $value) {
                   // 直播人推送
                    $trans=json_encode(array('pushCode'=>302,'objectId'=>$value['id'],'userId'=>0,'liveTitle' => $liveinfo['title']));
                    sock_post('http://localhost/Mapi/Tui/pushUid.html', array('uid'=>$value['user_id'],'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已终止','trans'=>$trans));

                }
                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }
    }

    public function ajaxLiveStatusOff($group_id){
        if($group_id){
            $this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();

            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,3);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                    'group_status' => 3,
                    'z_status' => 3,
                ));

               /*$mkHTML=new \Common\Util\makeHTML();
               $mkHTML-> ByGroupId($group_id);*/
                /*$action = A('Oss');
                foreach($ids as $k => $val) {
                     // 拉取回看m3u8地址

                    $mlist = $action->ajaxM3u8List($val['id']);
                    M('Live')->where(array('id' => $val['id']))->save(array(
                        'return_live' => $mlist[count($mlist) - 1]['RecordUrl'],
                    ));               
                }*/

                // 推送
                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $liveUserList = M('Live')->where(array('group_id' => $group_id))->select();
                $users = array();
                foreach($liveUserList as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value) 
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0)); 
                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $ids[0]['title'] . '》直播已结束','trans'=>$trans));
               // 直播人推送
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'申请人：' . $applyname . '的《' . $ids[0]['title'] . '》直播已结束','trans'=>$trans));


                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }

        }
    }

    public function ajaxLiveStatusOn(){
        $group_id=I('get.groupid');
        if($group_id){
            $this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();

            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,0);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                    'group_status' => 0,
                    'z_status' => 0,
                ));

                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/
                $action = A('Oss');
                foreach($ids as $k => $val) {
                    // 拉取回看m3u8地址

                    $mlist = $action->ajaxM3u8List($val['id']);
                    M('Live')->where(array('id' => $val['id']))->save(array(
                        'return_live' => $mlist[count($mlist) - 1]['RecordUrl'],
                    ));
                }

                // 推送
                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $liveUserList = M('Live')->where(array('group_id' => $group_id))->select();
                $users = array();
                foreach($liveUserList as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value)
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $ids[0]['title'] . '》直播已开始','trans'=>$trans));
                // 直播人推送
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'申请人：' . $applyname . '的《' . $ids[0]['title'] . '》直播已开始','trans'=>$trans));


                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }

        }
    }


    public function ajaxLiveOn(){
        // $live_id=I('get.liveId');
        // $stream=I('get.stream');
        // if($live_id&&$stream){
        //     $this->ajaxReturn(liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),2));
        // }

        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
            $count1 = M('Live')->where(array('group_id' => $group_id))->count();

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),2);
            if($res['status'] == 0) {
                $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 2))->count();
                if($count1 == $count2) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 2,
                    ));
                    $message['groupId']=2;
                }

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');

                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已开始','trans'=>$trans));

                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }

    }

    public function ajaxLiveOff(){
        // $live_id=I('get.liveId');
        // $stream=I('get.stream');
        // if($live_id&&$stream){
        //     $this->ajaxReturn(liveStatus(1, array(array('id'=>$live_id,'stream'=>$stream)),3));
        // }
        // 

        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
            $count1 = M('Live')->where(array('group_id' => $group_id))->count();

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),3);
            if($res['status'] == 0) {
                $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 3))->count();
                if($count1 == $count2) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 3,
                    ));
                    $message['groupId']=3;
                }

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');

                sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已结束','trans'=>$trans));

                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }

    }

//    public function showBTNs($id){
//        if($id){
//            $str='';
//            $zStatus=M('Live')->getFieldById($id,'z_status');
//            $info = M('Live')->where(array('id' => $id))->find();
//
//            $uid = session('liveadmin_uid');
//            $is_admin = session('is_admin');
//            $auth = M('LiveAuth')->where(array('group_id' => $info['group_id'], 'user_id' => $uid))->find();
//
//            switch($zStatus){
//                case 0:
//                    if($auth['is_manage'] == 1 || $is_admin == 1) {
//                        $str .='<span>直播通道</span><label class="switch"><input class="switch-input stream" name="single" id="single" type="checkbox" data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'" />';
//                        $str .= '<span class="switch-label" data-on="开" data-off="关"></span> <span class="switch-handle"></span> </label>';
//                    }
//                    $str .= '<span><img src="/Public/images/status-yellow.png" alt="" align="center"> 已审核</span>';
//                    break;
//                case 1:
//                    if($auth['is_manage'] == 1 || $is_admin == 1) {
//                        $str.='<span>直播通道</span><label class="switch"><input class="switch-input stream" name="single" id="single" type="checkbox" data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'" checked />';
//                        $str .= '<span class="switch-label" data-on="开" data-off="关"></span> <span class="switch-handle"></span> </label>';
//                    }
//                    $str .= '<span><img src="/Public/images/status-green.png" alt="" align="center"> 待直播</span>';
//                    break;
//                case 2:
//                    if($auth['is_manage'] == 1 || $is_admin == 1) {
//                        $checked = $info['z_status'] == 2 ? "checked" : "disable";
//                        $str .='<span>直播通道</span><label class="switch"><input class="switch-input stream" name="single" id="single" type="checkbox" data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'" checked />';
//                        $str .= '<span class="switch-label" data-on="开" data-off="关"></span> <span class="switch-handle"></span> </label>';
//                    }
//                    $str .= '<span><img src="/Public/images/status-red.png" alt="" align="center"> 直播中</span>';
//                    /*$str.='<span>直播状态</span><label class="switch"><input class="switch-input live" name="single" id="single" type="checkbox" data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'" ' . $checked . ' />';
//                    $str .= '<span class="switch-label" data-on="开" data-off="关"></span> <span class="switch-handle"></span> </label>';*/
//                    break;
//                case 3:
//                    $str = '<img src="/Public/images/status-gray.png" alt="" align="center"> 直播结束';
//                    break;
//            }
//            echo $str;
//        }
//    }


    public function showBTNs($id){
        if($id){
            $str='<div class="btn-group" role="group">';
            $zStatus=M('Live')->getFieldById($id,'z_status');
            $info = M('Live')->where(array('id' => $id))->find();

            $uid = session('liveadmin_uid');
            $is_admin = session('is_admin');
            $auth = M('LiveAuth')->where(array('group_id' => $info['group_id'], 'user_id' => $uid))->find();

            switch($zStatus){
                case 0:
                    if($auth['is_manage'] == 1 || $is_admin == 1) {
                        $str.='<botton type="button" class="btn btn-xs btn-success" disabled data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';

                        /*$str.='<botton type="button" class="btn btn-xs btn-default testing" data-status="4"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';*/
                    }
                    $str.='</div>';
                    $str .= ' <span><img src="/Public/images/status-yellow.png" alt="" align="center"> 已审核</span>';
                    break;
                case 2:
                    if($auth['is_manage'] == 1 || $is_admin == 1) {
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-success" data-status="1" disabled   data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';

                        /*$str.='<botton type="button" class="btn btn-xs btn-default testing" data-status="4"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';*/
                    }
                    $str.='</div>';
                    $str .= ' <span><img src="/Public/images/status-red.png" alt="" align="center"> 直播中</span>';
                    break;
                case 1:
                    if($auth['is_manage'] == 1 || $is_admin == 1) {
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-success" data-status="1" disabled   data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';

                        /*$str.='<botton type="button" class="btn btn-xs btn-default testing" data-status="4"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';*/
                    }
                    $str.='</div>';
                    $str .= ' <span><img src="/Public/images/status-green.png" alt="" align="center"> 待直播</span>';
                    break;


                case 3:
                    $str.='</div>';
                    $str = ' <img src="/Public/images/status-gray.png" alt="" align="center"> 直播结束';
                    break;

                /*case 4:
                    if($auth['is_manage'] == 1 || $is_admin == 1) {
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-success" data-status="4" disabled   data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';
                    }
                    $str.='</div>';
                    $str = ' <img src="/Public/images/status-gray.png" alt="" align="center"> 测试中';

                    break;*/
            }

            echo $str;
        }
    }

    public function ajaxDelLive(){
        if(IS_GET) {
            $id = I('get.id');
        } elseif(IS_POST) {
            $id = I('post.id');
            is_array($id) && $id = implode(',', $id);
        }

        if(empty($id)) {
            $message['status'] = -1;
            $message['msg'] = '选项不能为空';
            $this->ajaxReturn($message);
        }

        $map['group_id'] = array('in', $id);

        $res = M('Live')->where($map)->delete();
        if($res) {
            $message['status'] = 1;
            $message['msg'] = '删除成功';
            $this->ajaxReturn($message);
        } else {
            $message['status'] = -1;
            $message['msg'] = '删除失败，请重试';
            $this->ajaxReturn($message);
        }
    }

    public function _empty(){
        echo "";
    }

    public function ajaxEditPosName($id="",$posName=""){
        if($id && $posName){
            $group_id = M('Live')->where(array('id' => $id))->getField('group_id');
            $this->checkAuth($group_id);

            $data['id']=$id;
            $data['pos_name']=$posName;
            $res=M("Live")->save($data);
            if($res){
                $group_id=M('Live')->getFieldById($id,"group_id");
                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/
            }
            $this->ajaxReturn($res);
        }else{
            $this->ajaxReturn(0);
        }
    }

    public function updateDetail() {
        $live_intro = I('post.live_intro', '');
        $group_id = I('post.group_id', '');
        $title = I('post.title', '');
        $return_live = I('post.return_live', '');
        $start_time = I('post.start_time', 0);
        $filename = I("post.image_url");

        if($group_id) {
            $this->checkAuth($group_id);
            if($title) {

                  /*  if($_FILES['image_url']['size'] != 0) {
                        $upload = new \Think\Upload();// 实例化上传类
                        $upload->maxSize = 0 ;// 设置附件上传大小
                        $saveRule=$upload->saveRule = date('ymdHis', time()) . '_' . mt_rand(5);
                        $upload->autoSub = true;//使用子目录保存上传文件
                        $upload->subType = 'custom';//使用日期模式创建子目录
                        $upload->subName = date('Y') . '/' . date('m') . '/' . date('d');
                        $upload->dateFormat = 'Ymd';//设置子目录日期格式
                        $upload->allowExts  = array('gif', 'jpg', 'jpeg', 'png', 'bmp');// 设置附件上传类型
                        $upload->exts      = array('gif', 'jpg', 'jpeg', 'png', 'bmp');// 设置附件上传类型
                        $upload->rootPath  = './Html/Uploads/';
                        $upload->savePath =  'Live/';// 设置附件上传目录
                        $upload->thumb = false; //生成缩略图

                        // 上传文件
                        $info   =   $upload->upload();
                        if(!$info) {// 上传错误提示错误信息
                            $this->error($upload->getError());
                        }else{// 上传成功 获取上传文件信息
                            $filename = $info['image_url']['savepath'] . $info['image_url']['savename'];
                            $filename &&  $dataGet['image_url'] = $filename;
                        }

                    }*/

                    // $dataGet['title'] = $title;
                    // if($live_intro) {
                    //     $dataGet['intro'] = $live_intro;
                    // }

                    $title && $dataGet['title'] = $title;
                    $live_intro && $dataGet['intro'] = $live_intro;
                    $return_live && $dataGet['return_live'] = $return_live;
                    $start_time && $dataGet['start_time'] = strtotime($start_time);
                    if($filename){
                        $filename &&  $dataGet['image_url'] = $filename;
                    }


                    $res = M('Live')->where(array('group_id' => $group_id))->save($dataGet);

                    if($res !== false) {
                       /*$mkHTML=new \Common\Util\makeHTML();
                       $mkHTML-> ByGroupId($group_id);*/

                        $this->success('设置成功');
                    } else {
                        $this->error('设置失败，请重新操作');
                    }


            } else {
                $this->error('直播标题不能为空');
            }
        } else {
                $this->error('直播不存在');
            }
    }

    public function ajaxGetDetail() {
        $group_id = I('get.group_id', '');
        if($group_id) {
            $info = M('Live')->field('title, live_intro, image_url')->where(array('group_id' => $group_id))->find();
            if($info) {
                 $this->ajaxReturn($info);
            } else {
                $this->ajaxReturn(0);
            }

        } else {
            $this->ajaxReturn(0);
        }
    }

    /**
     * 直播流在线人数
     * @return [type] [description]
     */
    public function getOnlineNumber($sTime,$eTime) {
        $live_id = I('get.id');
        if($live_id) {
            $info = M('Live')->where(array('id' => $live_id))->find();
            if($info) {

                $info['Action'] = 'DescribeLiveStreamOnlineUserNum';
                $info['DomainName'] = 'jwlive.appwuhan.com';
                $info['AppName'] = 'jw';
                $info['StreamName'] = $info['group_id'] . '_' . $info['user_id'];

                $requestid = callAliyunApi($info); 
                $requestid = json_decode($requestid, true);
                if(isset($requestid['TotalUserNumber']) && isset($requestid['OnlineUserInfo'])) {
                    $message['status'] = 1;
                    $message['info'] = $requestid;
                    $this->ajaxReturn($message);                     
                }               

            } else {

                $message['status'] = -1;
                $message['msg'] = '直播不存在';               
            }

        } else {
            $message['status'] = -1;
            $message['msg'] = '未知ID';
        }   

        $this->ajaxReturn($message);    
    }
   

    /**
     * 根据ID获取指定的推流是否在线
     * @return [type] [description]
     */
    public function getStreamById() {
        $live_id = I('get.id');
        if($live_id) {
            $info = M('Live')->where(array('id' => $live_id))->find();
            if($info) {

                $info['Action'] = 'DescribeLiveStreamsOnlineList';
                $info['DomainName'] = 'jwlive.appwuhan.com';
                $info['AppName'] = 'jw';

                $requestid = callAliyunApi($info); 
                $requestid = json_decode($requestid, true);
                dump($requestid);
                // print_r($requestid);exit;
                if(isset($requestid['OnlineInfo']['LiveStreamOnlineInfo'])) {
                    if(!empty($requestid['OnlineInfo']['LiveStreamOnlineInfo'])) {
                        foreach($requestid['OnlineInfo']['LiveStreamOnlineInfo'] as $val) {
                            $streamName = $info['group_id'] . '_' . $info['user_id'];
                            if($val['StreamName'] == $streamName) {
                                $message['status'] = 1;
                                $message['is_push'] = 1; // 表示正在推流
                                $this->ajaxReturn($message);                                     
                            }
                        }

                    } else {

                        $message['status'] = 1;
                        $message['is_push'] = 0; // 表示未推流
                        $this->ajaxReturn($message);                          
                    }
                  
                }               

            } else {

                $message['status'] = -1;
                $message['msg'] = '直播不存在';               
            }

        } else {
            $message['status'] = -1;
            $message['msg'] = '未知ID';
        }   

        $this->ajaxReturn($message);  
    }

    public function ajaxGetSort() {
        $group_id = I('get.group_id');
        if($group_id) {
            $list = M('Live')->field('id, pos_sort')->where(array('group_id' => $group_id))->select();
            if($list) {
                $this->ajaxReturn($list);
            } else {
                $this->ajaxReturn(0);
            }

        } else {
            $this->ajaxReturn(0);
        }
    }

    public function ajaxUpdateSort() {
        $arr = I('post.data');
        $group_id = I('get.group_id');

        $this->checkAuth($group_id);    

        if($arr) {
            foreach($arr as $val) {
                $res = M('Live')->where(array('id' => $val[0]))->save(array(
                    'pos_sort' => intval($val[1]),
                ));
            }
           /*$mkHTML=new \Common\Util\makeHTML();
           $mkHTML-> ByGroupId($group_id);*/

            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }
/*
    public function ajaxReporterList() {
        $q = I('get.q');
        $group_id = I('get.group_id');

        $output = '';
        $auth = M('LiveAuth')->where(array('group_id' => $group_id))->getField('user_ids');
        $auth = unserialize($auth); 
        $con['uid'] = array('in', $auth);
        $authList = M('UserInfo')->where($con)->select();

        foreach($authList as $val) {
            $output .= '<li><input type="checkbox" name="id[]" value="' . $val['uid'] . '"</li><label>' . $val['realname'] . '</label>';
        }

        if($q) {
            $map['realname'] = $q;
            $map['mobile'] = $q;
            $map['realnamepy'] = $q;
            $map['_logic'] = 'OR';

            $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')
                    ->where($map)->select();
            $output .= '<hr />';
            foreach($list as $val) {
                $output .= '<li><input type="checkbox" name="id[]" value="' . $val['uid'] . '"</li><label>' . $val['realname'] . '</label>';
            }
        } 

        echo $output;
    }*/

     /**
     * 获取全部用户列表
     * @return [type] [description]
     */
    public function getReporterList() {
        $uid = session('liveadmin_uid');
        $channel = M('Admin')->where(array('id' => $uid))->getField('liveauth');
        
        $users = array();
        if($channel) {
            $map['userchannel'] = array('in', $channel);
            if($channel==='*'){
                $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')->select();
            }else{
                $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')->where($map)->select();
            }            
            foreach ($list as $key => $value) {
                $users[$key]['uid'] = $value['uid'];
                $users[$key]['realname'] = $value['realname'];
            }            
        }


        return $users;
    }   

    /**
     * 获取有权限的用户列表
     * @return [type] [description]
     */
    public function getReporterListByGroup($group_id) {

        $user_list = M('LiveAuth')->where(array('group_id' => $group_id))->select();
        $user_ids = array();

        foreach($user_list as $val) {
            $user_ids[] = $val['user_id'];
        }

        $users = array();
        if($user_ids) {
            $map['u.uid'] = array('in', $user_ids);
            $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')->where($map)->select();
            $users = array();
            foreach ($list as $key => $value) {
                $users[$key]['uid'] = $value['uid'];
                $users[$key]['realname'] = $value['realname'];
            }
        }

        return $users;
    }

    /**
     * 根据关键词搜索记者
     * @return [type] [description] 
     */
    public function getReporterListByKeyWords() {
        $q = I('get.q');
        $group_id = I('get.group_id');

        $list = array();
        if($q) {
            $map['realname'] = array('like', '%' . $q . '%');
            $map['mobile'] = $q;
            $map['realnamepy'] = array('like', '%' . $q . '%');
            $map['_logic'] = 'OR';

            $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')
                    ->where($map)->select();

        } 

        $this->ajaxReturn($list);  
    }

    /**
     * 添加用户权限
     * @return [type] [description]
     */
    public function ajaxAddReporter() {
        $uids = (array) I('post.uid');
        $group_id = I('get.group_id');
        $is_admin = session('is_admin');
        if($is_admin) {
            if($uids) {
                if($group_id) {
                    $model = M('LiveAuth');
                    foreach($uids as $val) {
                        $map['group_id'] = $group_id;
                        $map['user_id'] = $val;
                        $info = $model->where($map)->find();

                        $userArr = array();
                        if(!$info) {
                            $res = $model->add(array(
                                'group_id' => $group_id,
                                'user_id' => $val,
                                'is_scan' => 1,
                                'is_manage' => 1,
                            ));
                            $message['status'] = 1;
                            $message['msg'] = '添加成功';
                            $this->ajaxReturn($message);

                        } else {
                            $message['status'] = -1;
                            $message['msg'] = '已添加';
                            $this->ajaxReturn($message);
                        }
                    }


                } else {
                    $message['status'] = 0;
                    $message['msg'] = '无效参数';
                    $this->ajaxReturn($message);
                }
                
            } else {
                $message['status'] = 0;
                $message['msg'] = '无效参数';
                $this->ajaxReturn($message);
            }
        } else {
            $message['status'] = 0;
            $message['msg'] = '无权操作';
            $this->ajaxReturn($message);
        }
    }

    /**
     * 删除权限中的记者
     * @return [type] [description]
     */
    public function ajaxDelReporter() {
        $uid = I('post.uid');
        $group_id = I('get.group_id');
        $is_admin = session('is_admin');
        if($is_admin) {
            if($uid) {
                if($group_id) {
                    $res = M('LiveAuth')->where(array('group_id' => $group_id, 'user_id' => $uid))->delete();
                    if($res) {
                        $message['status'] = 1;
                        $message['msg'] = '删除成功';
                    } else {
                        $message['status'] = 0;
                        $message['msg'] = '删除失败';
                    }

                    $this->ajaxReturn($message);
                } else {
                    $message['status'] = 0;
                    $message['msg'] = '无效参数';
                    $this->ajaxReturn($message);                
                }

            } else {
                $message['status'] = 0;
                $message['msg'] = '无效参数';
                $this->ajaxReturn($message);
            }
        } else {
            $message['status'] = 0;
            $message['msg'] = '无权操作';
            $this->ajaxReturn($message);
        }
    }


    public function setLivePush() {
        $group_id = I('get.group_id');
        $status = I('post.status');

        $info = M('Live')->where(array('group_id' => $group_id))->find();
        if(!$info['image_url']) {
            $message['status'] = 2;
            $message['msg'] = '未上传图片';   
            $this->ajaxReturn($message);       
        }

        if($group_id) {
            $res = M('Live')->where(array('group_id' => $group_id))->save(array(
                'is_push' => $status
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $group_id))->find();
                $message['status'] = $status['is_push'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $message['status'] = 2;
                $message['msg'] = '操作失败，请重试';   
                $this->ajaxReturn($message); 
            }

        } else {
            $message['status'] = 2;
            $message['msg'] = '未知ID';   
            $this->ajaxReturn($message); 
        }
    }

   public function setLiveTop() {
        $group_id = I('get.group_id');
        $status = I('post.status');

        if($group_id) {
            $res = M('Live')->where(array('group_id' => $group_id))->save(array(
                'is_top' => $status
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $group_id))->find();
                $message['status'] = $status['is_top'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $this->ajaxReturn(0);
            }

        } else {
            $this->ajaxReturn(0);
        }
    }

    public function getRecordDetail() {
        $group_id = I('get.group_id');
        if($group_id) {
            $model = M('Pv');
            // $subQuery = 'SELECT COUNT(t.id) total FROM (SELECT id FROM `whtvjw_pv` WHERE `group_id` = "' . $group_id . '" GROUP BY ip) t';
            // $seeTotal = M()->query($subQuery);
            // $count = $seeTotal[0]['total'];
            // $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            // $show       = $Page->show();// 分页显示输出
            $list = $model->where(array('group_id' => $group_id))->group('ip')->select();

            $this->ajaxReturn($list);

        } else {
            $this->ajaxReturn(0);
        }
    } 

    /**
     * 上传每个机位的缩略图
     * @return [type] [description]
     */
    public function uploadLiveThumb() {
        $upload_ret=I('get.upload_ret');
        $upload_ret=json_decode(\Qiniu\base64_urlSafeDecode($upload_ret),true);


        $filename =is_array($upload_ret)?$upload_ret['filename']:"";
        $live_id = is_array($upload_ret)?$upload_ret['liveId']:"";
        if($live_id) {
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
            $this->checkAuth($group_id);

            if($filename) {
                $dataGet['thumb'] = C('IMAGE_HOST').$filename;
                $dataGet['id'] = $live_id;

                $res = M('Live')->save($dataGet);

                if($res !== false) {
                   /*$mkHTML = new \Common\Util\makeHTML();
                   $mkHTML-> ByGroupId($group_id);*/
                    $this->success('设置成功',U('liveInfo',array('group_id'=>$group_id)));
                } else {
                    $this->error('设置失败，请重新操作',U('liveInfo',array('group_id'=>$group_id)));
                }


            } else {
                $this->error('上传失败',U('liveInfo',array('group_id'=>$group_id)));
            }
     
        } else {
                $this->error('直播不存在',U('index'));
        }        
    }

    public function getLiveThumb() {
        $live_id = I('get.liveid', 0);
        if($live_id) {
            $thumb = M('Live')->where(array('id' => $live_id))->getField('thumb');

            $this->ajaxReturn($thumb);
        } else {
            $this->ajaxReturn(0);
        }
    }

    public function ajaxSetTheme(){
        $liveid=I('get.liveid');
        $themeid=I('get.themeid');
        if($liveid!='' && $liveid!=''){
            $liveid=$liveid==0?null:$liveid;
            $res = M('Live')->where(array('group_id' => $liveid))->save(array(
                'theme_id' => $themeid
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $liveid))->find();
                $message['status'] = $status['theme_id'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $this->ajaxReturn(0);
            }
        }else{
            $this->ajaxReturn(0);
        }
    }

    public function addClicks($live_id,$num){
        sock_get('http://localhost/Live/Live/clicksNum.html',array('live_id'=>$live_id,'num'=>$num));
    }

    public function clicksNum($live_id,$num){
        ini_set("max_execution_time", 0);
        $rand=M('Live')->getFieldById('rand',$live_id);
        while($rand<$num){
            $n=rand(2,8);
            M('Live')->where(array('id'=>$live_id))->setInc('rand',$n); 
            $rand+=$n;
            sleep(rand(2,5));
        }
    }

    /**
     * 查询直播流的帧率和码率
     * @return [type] [description]
     */
    public function getLiveStreamsFrameRateAndBitRate($id='',$sTime=0,$eTime='') {
        $flag = I('get.flag', 1);
        if($id){
            //date_default_timezone_set("Etc/GMT");
            if(!$eTime){
                $eTime=date(DATE_ISO8601,time()-8*3600).'Z';
            }else{
                $eTime=date(DATE_ISO8601,strtotime($eTime.' 23:59:59')-8*3600).'Z';
            }

            $eTime=str_replace("+0800","",$eTime);
            if(!$sTime){
                $sTime=date(DATE_ISO8601, time() - 7 * 24 * 60 * 60-8*3600).'Z';
            }else{
                $sTime=date(DATE_ISO8601,strtotime($sTime.' 00:00:00')-8*3600).'Z';
            }
            $sTime=str_replace("+0800","",$sTime);

            $live=M('Live')->field('id,group_id,realnamepy,userchannel,apply_time,user_id,return_live')
                ->alias('l')
                ->join('__USER_INFO__ ui on l.user_id=ui.uid')
                ->find($id);
            if($live['userchannel']==55 || $live['is_device']==1){
                $stream=$live['realnamepy'];
            }else{
                $stream=$live['group_id'].'_'.$live['user_id'];
            }

            $info['Action'] = 'DescribeLiveStreamsFrameRateAndBitRateData';
            $info['DomainName'] = 'jwlive.appwuhan.com';
            $info['AppName'] = 'jw';
            $info['StreamName'] = $stream;
            $info['StartTime'] = $sTime;
            $info['EndTime'] = $eTime;

            $requestid = callAliyunApi($info);
            $requestid = json_decode($requestid, true);

            $str = '';
            $arr=array();
            if(count($requestid['FrameRateAndBitRateInfos']['FrameRateAndBitRateInfo'])==0){
                if($flag) {
                    $this->ajaxReturn(array('code'=>0,'msg'=>'没有数据'));
                } else{
                    echo ('<div class="alert alert-info" role="alert">没有数据</div>');
                } 

            }else{
                foreach($requestid['FrameRateAndBitRateInfos']['FrameRateAndBitRateInfo'] as $k=>$v){
                    $str.='<li><div class="intervalTime">'.($k+1) .'、'.date("Y-m-d H:i",strtotime(str_replace("Z",'-08:00',$v['Time']))) . '</div>';

                    $str .= '<div class="details">
                        <p>直播流：' . $v['StreamUrl'] . '</p>
                        <p>视频帧率：' . $v['VideoFrameRate'] . '</p>
                        <p>音频帧率：' . $v['AudioFrameRate'] . '</p>
                        <p>码率：' . $v['BitRate'] . '</p>
                    </div>';
                    $str.='</li>';

                    $arr['BitRate'][]=array(
                                (strtotime($v['Time'])+8*3600)*1000,
                                $v['BitRate']
                            );
                        $arr['VideoFrameRate'][]=array(
                                (strtotime($v['Time'])+8*3600)*1000,
                                $v['VideoFrameRate']
                            );
                        $arr['AudioFrameRate'][]=array(
                                (strtotime($v['Time'])+8*3600)*1000,
                                $v['AudioFrameRate']
                            );
                }

                $arr['BitRate']=array_reverse($arr['BitRate']);
                $arr['VideoFrameRate']=array_reverse($arr['VideoFrameRate']);
                $arr['AudioFrameRate']=array_reverse($arr['AudioFrameRate']);
                if($flag) {

                    $this->ajaxReturn($arr);
                } else{
                    echo $str;
                }
               
            }
        }else{
            if($flag) {
                $this->ajaxReturn(0);
            } else{
                echo ('<div class="alert alert-danger" role="alert">参数错误！</div>');
            }
        }
    }

    public function ajaxEditReturnLive(){
        if(IS_POST){
            $id=I('post.id');
            $return_live=I('post.returnLive');
            if($id && $return_live){
                $res=M('Live')->save(array('id'=>$id,'return_live'=>$return_live));
                echo $res;
            }else{
               $this->ajaxReturn(-1);
            }
        }else{
            $this->ajaxReturn(-1);
        }
    }

    public function ajaxGetLongRtmp($id){
        if($id){
            $res=M('Live')->alias('l')->join('__USER_INFO__ ui on l.user_id=ui.uid')->find($id);
            if($res){
                if($res['userchannel']==55 || $res['is_device']==1){
                    $stream="rtmp://jwlive.appwuhan.com/jw/" . $res['realnamepy'];
                } elseif($res['userchannel']==57) {
                    $stream="rtmp://jwlive.appwuhan.com/jwdev/" . $res['group_id'].'_'.$res['user_id'];
                }else{
                    $stream="rtmp://jwlive.appwuhan.com/jw/" . $res['group_id'].'_'.$res['user_id'];
                }
                echo authAliyun($stream,time()+3600*24*2);
            }else{
                ehco -1;
            }
        }
    }

     public function ajaxGetLongM3u8($id){
        if($id){
            $res=M('Live')->alias('l')->join('__USER_INFO__ ui on l.user_id=ui.uid')->find($id);
            if($res){
                if($res['userchannel']==55 || $res['is_device']==1){
                    $stream="http://jwlive.appwuhan.com/jw/" . $res['realnamepy'].'.m3u8';
                } elseif($res['userchannel']==57) {
                    $stream="http://jwlive.appwuhan.com/jwdev/" . $res['group_id'].'_'.$res['user_id'].'.m3u8';
                }else{
                    $stream="http://jwlive.appwuhan.com/jw/" . $res['group_id'].'_'.$res['user_id'].'.m3u8';
                }
                echo authAliyun($stream,time()+3600*24*2);
            }else{
                ehco -1;
            }
        }
    }


    public function ajaxGetLongPushRtmp($id){
        if($id){
            $res=M('Live')->alias('l')->join('__USER_INFO__ ui on l.user_id=ui.uid')->find($id);
            if($res){
                if($res['userchannel']==55 || $res['is_device']==1){
                    $stream = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $res['realnamepy'] . '?vhost=jwlive.appwuhan.com',time()+3600*24*365);
                } elseif($res['userchannel']==57) {
                    $stream = authAliyun('rtmp://video-center.alivecdn.com/jwdev/' . $res['group_id'] . '_' . $res['user_id'] . '?vhost=jwlive.appwuhan.com',time()+3600*24*3);
                }else{
                    $stream = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $res['group_id'] . '_' . $res['user_id'] . '?vhost=jwlive.appwuhan.com',time()+3600*24*3);
                }

                echo $stream;
            }else{
                ehco -1;
            }
        }
    }

   public function ajaxSetLiveStatus(){
       $group_id=I('get.group_id');
       $status=I('get.status');

       switch($status){
           case 0:
               $this->ajaxGroupStreamOff($group_id);
               break;
           case 1:
               $this->ajaxGroupStreamOn($group_id);
               break;
           case 4:
               $this->ajaxGroupTesting($group_id);
               break;
           case 3:
               $this->ajaxLiveStatusOff($group_id);
               break;
       }
   }


   public function ajaxSetSort(){
       $thisGroupId=I('get.thisId');
       $thatGroupId=I('get.thatId');

       if($thisGroupId && $thatGroupId){
           $thisRes=M('Live')->where(array('group_id'=>$thisGroupId))->find();
           $thatRes=M('Live')->where(array('group_id'=>$thatGroupId))->find();

           M()->startTrans();

           if($thisRes['pos_sort']==$thatRes['pos_sort']){
               $res1=M('Live')->where(array('group_id'=>$thisGroupId))->save(array('sort_by_id'=>$thatRes['sort_by_id']));
               $res2=M('Live')->where(array('group_id'=>$thatGroupId))->save(array('sort_by_id'=>$thisRes['sort_by_id']));
           }else{
               $res1=M('Live')->where(array('group_id'=>$thisGroupId))->save(array('sort'=>$thatRes['sort']));
               echo M()->_sql();
               $res2=M('Live')->where(array('group_id'=>$thatGroupId))->save(array('sort'=>$thisRes['sort']));
               echo M()->_sql();
           }

           if($res1===false || $res2===false){
               echo false;
               M()->rollback();

           }else{
               echo true;
               M()->commit();
           }
       }else{
           echo false;
       }

   }

   public function setLiveVerify() {
        $group_id = I('get.group_id');
        $status = I('post.status');

        $info = M('Live')->where(array('group_id' => $group_id))->find();
        if(!$info) {
            $message['status'] = -1;
            $message['msg'] = '直播信息有误';   
            $this->ajaxReturn($message);       
        }

        if($group_id) {
            $res = M('Live')->where(array('group_id' => $group_id))->save(array(
                'is_verify' => $status
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $group_id))->find();
                $message['status'] = $status['is_verify'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $message['status'] = -1;
                $message['msg'] = '操作失败，请重试';   
                $this->ajaxReturn($message); 
            }

        } else {
            $message['status'] = -1;
            $message['msg'] = '未知ID';   
            $this->ajaxReturn($message); 
        }
    }

    public function add_live(){
        if(IS_POST) {
            $model = D('Live');
            $dataGet['title'] = I('post.addLiveTitle');
            $user_ids = trim(I('post.addLiveUsers', ''),","); // 直播人ID
            $dataGet['start_time'] = time();
            $dataGet['address'] = "";
            $dataGet['intro'] = "";
            $dataGet['v_status'] = 1;
            $dataGet['apply_id'] = 0;
            $group = date('YmdHis') . '_' . $this->uid . '_' . uniqid(); // 祖名

            $user_ids = $user_ids ? explode(',', $user_ids) : array();

 
            $channelres=M('UserInfo')->alias('ui')
                ->join('__CHANNEL__ c on ui.userchannel=c.chid')
                ->where(array('ui.uid' => $user_ids[0]))->find();
            $dataGet['column_id'] = $channelres['userchannel'];
            $dataGet['create_time'] = time();
            $dataGet['update_time'] = time();
            $dataGet['rand'] = rand(6600, 6800);

            if($model->create($dataGet)) {
                try {
                    M()->startTrans();
                    if($user_ids) {
                        foreach($user_ids as $k => $id) {
                            $dataGet['user_id'] = $id;
                            $dataGet['apply_id'] = 0;
                            $dataGet['group_id'] = $group;
                            // $dataGet['url'] = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $group . '_' . $id . '?vhost=jwlive.appwuhan.com');
                            // $dataGet['url'] = 'rtmp://video-center.alivecdn.com/jw/' . $group . '_' . $id . '?vhost=jwlive.appwuhan.com';
                            // $dataGet['bo_url'] = 'rtmp://jwlive.appwuhan.com/jw/' . $group . '_' . $id;
                            $dataGet['group_num'] = implode(',', array_reverse($user_ids));

                            $tmp[$k]['id'] = $id;
                            $tmp[$k]['stream'] = $group . '_' . $id;

                            liveStatus(2, $tmp, -1);

                            $res = $model->add($dataGet);
                            if(!$res)
                                throw new \Exception('服务器异常');
                        }

                    } else {
                        throw new \Exception('申请失败，请重试');
                    }

                    M()->commit();

                    $message['resultCode'] = 0;
                    $message['message'] = '申请成功';


                } catch (\Exception $e) {
                    M()->rollback();
                    $message['resultCode'] = 1;
                    $message['message'] = $e->getMessage();
                    $this->error($e->getMessage());
                }

            } else {
                $message['resultCode'] = 1;
                $message['message'] = $model->getError();
                $this->error($message['message']);
            }

        } else {
            $message['resultCode'] = 1;
            $message['message'] = '非法请求';
            $this->error($message['message']);
        }

        $this->success($message['message'],U('live_list'));
    }

}